Searching the array for multiple values

55

Searching the array for multiple values -

# Searching the array for multiple values corresponds to the set operations (set difference and intersection), as you will see below.

# In your question, you do not specify which type of array search you want, so I am giving you both options.

# ALL needles exist
function in_array_all($needles, $haystack) {
   return empty(array_diff($needles, $haystack));
}

$animals = ["bear", "tiger", "zebra"];
echo in_array_all(["bear", "zebra"], $animals); // true, both are animals
echo in_array_all(["bear", "toaster"], $animals); // false, toaster is not an animal

# ANY of the needles exist
function in_array_any($needles, $haystack) {
   return !empty(array_intersect($needles, $haystack));
}

$animals = ["bear", "tiger", "zebra"];
echo in_array_any(["toaster", "tiger"], $animals); // true, tiger is an amimal
echo in_array_any(["toaster", "brush"], $animals); // false, no animals here

# Important consideration
/*
If the set of needles you are searching for is small and known upfront, your code might be clearer if you just use the logical chaining of in_array calls, for example:
*/
$animals = ZooAPI.getAllAnimals();
$all = in_array("tiger", $animals) && in_array("toaster", $animals) && ...
$any = in_array("bear", $animals) || in_array("zebra", $animals) || ...

Comments

Submit
0 Comments